layui.extend({
    dtree: '/evaluation/public/layui_ext/dtree/dtree'   // {/}的意思即代表采用自有路径，即不跟随 base 路径
}).use(['dtree', 'layer', "form", "table"], () => (function (
    {dtree, layer, form, table, evaluatMemberFalseTableIns, evaluatMemberTureTableIns, FalseArr, FalseResArr, TureArr, TureResArr, SelectDatas, removeByValue, DemoTree, TreeCheckedData, url, contentType, page, ok, AjaxFn}) {

        /*http://www.wisdomelon.com/DTreeHelper/*/
        /*树加载渲染*/
        DemoTree = dtree.render({
        elem: "#demoTree",
        url: url + 'treeDatas',
        method: 'post',
        contentType,
        dataType: 'json',
        dataStyle: "layuiStyle",
        ficon: ["2", "-1"],
        icon: ["-1", "-1"],
        scroll: "#div-tree",
        skin: "zdy",
        menubar: true,
        menubarTips: {
            freedom: [
                {
                    menubarId: "add",
                    handler: (node, message = {}) => (
                        message.title = "请输入评定组名称", message.maxlength = 50,

                        layer.prompt(message, (val, index) => (res = AjaxFn(url + "treeDatasAdd", JSON.stringify({vcustomername: val.trim()}), {}),

                            {code, msg} = res, code == 200 ?

                            layer.alert(msg, {icon: 1,skin: 'add-alert-class'}, () => (layer.closeAll(), dtree.reload(DemoTree))) : layer.msg(msg, {icon: 5,time:1000}))))
                },
                {
                    menubarId: "updata",
                    handler: (node, message = {}) => (
                        $.isEmptyObject(node) || node.parentId == 0 ? layer.msg('请选择子节点', {icon: 7}) : (
                            {nodeId: vcustomerid, context} = node,
                            message.title = "请输入评定组名称", message.maxlength = 50, message.value = context,
                            layer.prompt(message, (val, index, param = {}) => (
                                    param.vcustomerid = vcustomerid, param.vcustomername = val.trim(), val != context ? (
                                    res = AjaxFn(url + "treeDatasUpdata", JSON.stringify(param), {}),
                                    {code, msg} = res, code == 200 ?
                                    layer.alert(msg, {icon: 1, skin: 'add-alert-class'}, () => (layer.closeAll(), dtree.reload(DemoTree))) :
                                    layer.msg(msg, {icon: 5,time:1000})) : layer.closeAll()
                                )
                            )
                        )
                    )
                },
                {
                    menubarId: "del", handler: function (node) {//&& TreeCheckedData
                        $.isEmptyObject(node) || node.parentId == 0 && TreeCheckedData ? layer.msg('请选择子节点', {icon: 7}) :
                            ({nodeId: vcustomerid} = node, layer.confirm('确定删除该评定组吗？', {
                                id: "del",
                                icon: 6,
                                title: '提示',
                                skin: 'del-confirm-class',
                                btn: ['取消','确定'],
                                success: (layero) => (btn = layero[0].getElementsByClassName('layui-layer-btn')[0].getElementsByTagName('A')[0], btn.href = 'javascript:void(0)', btn.focus()),
                                btn2: (index, layero) => (res = AjaxFn(url + "treeDatasDel", JSON.stringify({vcustomerid}), {}), {code, msg} = res, code == 200 ? layer.alert(msg, {icon: 1, skin: 'add-alert-class',closeBtn:0}, () => (layer.closeAll(), dtree.reload(DemoTree), evaluatMemberFalseTableIns.reload(), evaluatMemberTureTableIns.reload(),TreeCheckedData={})) : layer.msg(msg, {icon: 5})),
                            }))
                    }
                },
            ],
            group: []
        },
    }),

        /*筛选条件加载渲染*/
        SelectDatas = ((data) => (data = AjaxFn("/evaluation/staff/staffSelectDatas", "", {}), {
            positions = [],
            teams = [],
            factorys = [],
            appraises = [],
            o = '<option value=""></option>',
            p = ""
        } = data, SelectDatas = data, positions.length > 0 ? (() => (p = o, $.each(positions, (i, v) => p += `<option value="${v.vpositionid}">${v.vpositionname}</option>`), $("select[name=vpositionid]").html(p), p = ''))() : '', factorys.length > 0 ? (() => (p = o, $.each(factorys, (i, v) => p += `<option value="${v.scode}">${v.vname}</option>`), $("select[name=vfactoryflg]").html(p), p = ''))() : '', teams.length > 0 ? (() => (p = o, $.each(teams, (i, v) => p += `<option value="${v.vteamid}">${v.vteamname}</option>`), $("select[name=vteamid]").html(p), p = ""))() : ''))({}), form.render(),

        // 绑定节点点击
        dtree.on("node('demoTree')", (obj) => (TreeCheckedData = obj.param, evaluatMemberTureTableIns = table.reload("evaluatMemberTure", {
            where: {vpositionid: TreeCheckedData.nodeId},
            method: 'post',
            contentType,
            url: url + "evaluatMemberTure"
        }))),

        /*未选中员工 table 初始化*/
        evaluatMemberFalseTableIns = table.render({
            elem: '#evaluatMemberFalse',
            id:'evaluatMemberFalse',
            url: url + "evaluatMemberFalse",
            method: 'post',
            skin:'evaluatMemberFalse',
            contentType,
            page,
            cols: [
                [
                    {type: 'checkbox', fixed: "left", unresize: true, align: "center", minWidth: 20},
                    {field: 'vstaffname', title: '员工名称', fixed: "left", unresize: true, align: "center", minWidth: 100},
                    {field: 'vpositionname', title: '职位', unresize: true, align: "center", minWidth: 100},
                    {field: 'vfactoryflgname', title: '工厂', unresize: true, align: "center", minWidth: 100},
                    {field: 'vteamname', title: '班组', unresize: true, align: "center", minWidth: 80},
                    {field: 'vphone', title: '手机号', unresize: true, align: "center", minWidth: 120},
                    {field: 'vappraiseflgname', title: '评定组', unresize: true, align: "center", minWidth: 80},
                ]
            ],
            done: function (res, curr, count) {
                FalseResArr = res.data;
                console.log("res.data==",res.data);
                console.log("FalseArr==",FalseArr);
                for (var i = 0; i < res.data.length; i++) {
                    for (var j = 0; j < FalseArr.length; j++) {
                        //数据id和要勾选的id相同时checkbox选中
                        if (res.data[i].vstaffid == FalseArr[j].vstaffid) {
                            console.log(res.data[i]);
                            //这里才是真正的有效勾选
                            res.data[i]["LAY_CHECKED"] = 'true';
                            //找到对应数据改变勾选样式，呈现出选中效果
                            var index = res.data[i]['LAY_TABLE_INDEX'];
                            $('.div-False-table .layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                            $('.div-False-table .layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                        }
                    }
                }
                var checkStatus = table.checkStatus('evaluatMemberFalse');//这里的studentTable是指分页中的id
                if (checkStatus.isAll) {
                    //layTableAllChoose
                    /*$('.layui-table th[data-field="0"] input[type="checkbox"]').prop('checked', true);//data-field值默认为0，如果在分页部分自定义了属性名，则需要改成对应的属性名
                    $('.layui-table th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');//data-field值默认为0，如果在分页部分自定义了属性名，则需要改成对应的属性名
                */
                   $('.div-False-table .layui-table th[data-field="0"] input[type="checkbox"]').prop('checked', true);//data-field值默认为0，如果在分页部分自定义了属性名，则需要改成对应的属性名
                    $('.div-False-table .layui-table th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');//data-field值默认为0，如果在分页部分自定义了属性名，则需要改成对应的属性名


                }
            }
        }),

        /*未选中员工 table checkbox 点击事件*/
        table.on('checkbox(evaluatMemberFalse)', ({checked, data, type}) => (/*FalseArr,FalseResArr*/checked ? (type == 'one' ? (FalseArr.push(data)) : ($.each(FalseResArr, (i, v) => (arrindex = FalseArr.findIndex(fv => fv.vstaffid == v.vstaffid), arrindex == -1 ? FalseArr.push(v) : '')))) : (type == 'one' ? (FalseArr.splice(FalseArr.findIndex(v => v.vstaffid == data.vstaffid), 1)) : ($.each(FalseResArr, (i, v) => (FalseArr.splice(FalseArr.findIndex(fv => fv.vstaffid == v.vstaffid), 1))))), FalseArr.length > 0 ? $(".btn-right").addClass("btn-right-add") : $(".btn-right").removeClass("btn-right-add"))),

        /*移入 按钮 点击事件*/
        $(".btn-right").click((param) => (/*tableIns.reload("scoreinfoTable",{data:scoreinfos});*/$.isEmptyObject(TreeCheckedData) || TreeCheckedData.parentId == 0 ? layer.msg("请选择一个评定组", {icon: 7}) : FalseArr.length > 0 ? (param.vpositionid = TreeCheckedData.nodeId, param.FalseArr = FalseArr, res = AjaxFn(url + "evaluatMemberTrueAdd", JSON.stringify(param), {}), {
            code,
            msg
        } = res,code == 200 ? (evaluatMemberFalseTableIns.reload(), evaluatMemberTureTableIns.reload(), $(".btn-right").removeClass("btn-right-add"), FalseArr = []) : layer.msg(msg, {icon: 5})) : layer.msg("请选择要移入的员工", {icon: 7}))),

        /*已选中员工 table 初始化*/
        evaluatMemberTureTableIns = table.render({
            elem: '#evaluatMemberTure',
            page,
            cols: [
                [
                    {type: 'checkbox', fixed: "left", unresize: true, align: "center", minWidth: 20},
                    {field: 'vstaffname', title: '员工名称', fixed: "left", unresize: true, align: "center", minWidth: 100},
                    {field: 'vpositionname', title: '职位', unresize: true, align: "center", minWidth: 100},
                    {field: 'vfactoryflgname', title: '工厂', unresize: true, align: "center", minWidth: 100},
                    {field: 'vteamname', title: '班组', unresize: true, align: "center", minWidth: 80},
                    {field: 'vphone', title: '手机号', unresize: true, align: "center", minWidth: 120},
                    {field: 'vappraiseflgname', title: '评定组', unresize: true, align: "center", minWidth: 80},
                ]
            ],
            data: [],
            done: function (res, curr, count) { //TureArr,TureResArr
                TureResArr = res.data;
                for (var i = 0; i < res.data.length; i++) {
                    for (var j = 0; j < TureArr.length; j++) {
                        //数据id和要勾选的id相同时checkbox选中
                        if (res.data[i].vstaffid == TureArr[j].vstaffid) {
                            console.log(res.data[i]);
                            //这里才是真正的有效勾选
                            res.data[i]["LAY_CHECKED"] = 'true';
                            //找到对应数据改变勾选样式，呈现出选中效果
                            var index = res.data[i]['LAY_TABLE_INDEX'];
                            $('.div-Ture-table .layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                            $('.div-Ture-table .layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                        }
                    }
                }
                var checkStatus = table.checkStatus('evaluatMemberTure');
                if (checkStatus.isAll) {
                    $('.div-Ture-table .layui-table th[data-field="0"] input[type="checkbox"]').prop('checked', true);//data-field值默认为0，如果在分页部分自定义了属性名，则需要改成对应的属性名
                    $('.div-Ture-table .layui-table th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');//data-field值默认为0，如果在分页部分自定义了属性名，则需要改成对应的属性名
                }
            }
        }),

        /*已选中员工 table checkbox 点击事件*/
        table.on('checkbox(evaluatMemberTure)', ({checked, data, type}) => (/*TureArr,TureResArr*/checked ? (type == 'one' ? (TureArr.push(data)) : ($.each(TureResArr, (i, v) => (arrindex = TureArr.findIndex(fv => fv.vstaffid == v.vstaffid), arrindex == -1 ? TureArr.push(v) : '')))) : (type == 'one' ? (TureArr.splice(TureArr.findIndex(v => v.vstaffid == data.vstaffid), 1)) : ($.each(TureResArr, (i, v) => (TureArr.splice(TureArr.findIndex(fv => fv.vstaffid == v.vstaffid), 1))))), TureArr.length > 0 ? $(".btn-left").addClass("btn-right-add") : $(".btn-left").removeClass("btn-right-add"))),
        /*移出 按钮 点击事件*/
        $(".btn-left").click((param) => (/*tableIns.reload("scoreinfoTable",{data:scoreinfos})*/$.isEmptyObject(TreeCheckedData) || TreeCheckedData.parentId == 0 ? layer.msg("请选择一个评定组", {icon: 7}) : TureArr.length > 0 ? (param.vpositionid = TreeCheckedData.nodeId, param.TureArr = TureArr, res = AjaxFn(url + "evaluatMemberTrueDel", JSON.stringify(param), {}), {
            code,
            msg
        } = res,code == 200 ? (evaluatMemberFalseTableIns.reload(), evaluatMemberTureTableIns.reload(), $(".btn-left").removeClass("btn-right-add"), TureArr = []) : layer.msg(msg, {icon: 5})) : layer.msg("请选择要移出的员工", {icon: 7}))),

        /*未选中员工 table 筛选 查询 按钮点击事件*/
        form.on('submit(FalseSel)', function ({field}) {
            evaluatMemberFalseTableIns.reload({
                where: field,
                page: {curr: 1}
            })
            return false;
        }),
        /*已选中员工 table 筛选 查询 按钮点击事件*/
        form.on('submit(TureSel)', function ({field}) {
            $.isEmptyObject(TreeCheckedData) ? layer.msg("请选择一个评定组", {icon: 7}) :
                (() => (
                    {vpositionid: svpositionid, vfactoryflg, vteamid,} = field,
                        evaluatMemberTureTableIns = table.reload("evaluatMemberTure", {
                            where: {svpositionid, vfactoryflg, vteamid, vpositionid: TreeCheckedData.nodeId},
                            method: 'post', contentType,
                            url: url + "evaluatMemberTure"
                        })
                ))()
            return false;
        })


})({
    dtree: layui.dtree,
    layer: layui.layer,
    form: layui.form,
    table: layui.table,
    evaluatMemberFalseTableIns: '',
    evaluatMemberTureTableIns: '',
    FalseArr: [],
    FalseResArr: [],
    TureArr: [],
    TureResArr: [],
    DemoTree: '',
    SelectDatas: {},
    TreeCheckedData: {},
    removeByValue: function (arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    },
    url: "/evaluation/customerAssessment/",
    contentType: 'application/json;charset=utf-8',
    page: {
        first: '首页',
        last: '尾页',
        prev: '上一页',
        next: '下一页',
        layout: ['count', 'prev', 'page', 'next'],
        groups: 5,
        theme: '#1e9fff',
        limits: [10, 20, 30, 40, 50],
    },
    ok: function (msg, icon) {
        layui.layer.confirm(msg, {
            id: "ok",
            icon: icon,
            anim: 4,
            title: '提示',
            btn: ['确定'],
            closeBtn: false,
            success: function (layero) {
                var btn = layero[0].getElementsByClassName('layui-layer-btn')[0].getElementsByTagName('A')[0];
                btn.href = 'javascript:void(0)';
                btn.focus();
            },
            yes: function (index, layero) {
                layer.close(index); //再执行关闭
            },
            end: function () {
                var index2 = parent.layer.getFrameIndex(window.name);
                parent.layer.closeAll();
            }
        });
    },
    AjaxFn: function (url, data, resource) {
        $.ajax({
            url,
            contentType: 'application/json;charset=utf-8',
            type: 'post',
            async: false,
            data,
            success: function (res) {
                let {msg='',code=''} =res;
                msg=='' && code==''? top.location.reload() : "";
                resource = res;
            }
        });
        return resource;
    }
}))


















